import { create } from "zustand";
import { combine } from "zustand/middleware";
import { request, ResBody, _AxiosRequestConfig } from "../common/request";
import { UserModel } from "../common/model";

export const useAuthStore = create(
  combine(
    {
      user: undefined as undefined | UserModel,
      loading: true,
    },
    (set, get) => ({
      setUser: (user?: UserModel) => {
        set({ user });
      },
      loadUserInfo: async () => {
        //已存在就不再加载
        if (get().user) {
          return;
        }
        //加载用户信息
        const ret = await request.get<any, ResBody>(`/api/user/info`, {
          noErrMessage: true,
        } as _AxiosRequestConfig);

        if (ret.code === 200) {
          set({ user: ret.user, loading: false });
        } else {
          set({ loading: false });
        }
      },
      logout: () => {
        localStorage.removeItem("token");
        set({ user: undefined });
      },
      login: async (token: string, user: UserModel) => {
        localStorage.setItem("token", token);
        set({ user });
      },
    })
  )
);
